<template></template>
<script lang="ts">
import { defineComponent, onMounted, nextTick, watch } from "vue";
import { showToast } from "vant";
import { UserModule } from "@/store/modules/user";
import { versig, verifyToken } from "@/api";
import { Set_App_Token_Key, Get_App_Token_Key } from "@/utils/auth";
import { FormatDate } from "@/utils/formatDate";

export default defineComponent({
    emits: ["load"],
    setup(props, ctx) {
        const sendRegister = async (): Promise<void> => {
            try {
                const message =
                    "welcome to login tronbank.pro.stake at " +
                    FormatDate(new Date(), "yyyy-MM-dd hh:mm:ss");
                const sign = await tronWeb.trx.signMessageV2(message);
                const res = await versig({
                    message: message,
                    signature: sign,
                });
                if (res.data.code == 20) {
                    const key = {
                        ...Get_App_Token_Key(),
                        [UserModule.userAddr]: res.data.data.Token,
                    };
                    Set_App_Token_Key(key);
                    ctx.emit("load");
                    const userAddr = UserModule.userAddr;
                    UserModule.SET_USERADDR("");
                    await nextTick(() => {
                        UserModule.SET_USERADDR(userAddr as string);
                    });
                } else {
                    showToast(res.data.message);
                }
            } catch (error: any) {
                showToast(error);
            }
        };
        onMounted(async () => {});
        watch(
            () => UserModule.userAddr,
            (newUserAddr: string) => {
                if (newUserAddr) {
                    verifyToken().then((res) => {
                        if (res.data.code != 20) {
                            sendRegister();
                        }
                    });
                }
            },
            { immediate: true }
        );
        return {
            UserModule,
            sendRegister,
        };
    },
});
</script>
<style lang="less" scoped></style>
